//
//  main.m
//  WSPluginSwitcher
//
//  Created by Marc Bauer on 17.01.09.
//  Copyright 2009 nesiumdotcom. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "Worker.h"

int main (int argc, const char * argv[])
{
	if (geteuid() != 0)
	{
		//NSLog(@"not running as root");
		exit(-1);
	}
	
	AuthorizationRef auth;
	AuthorizationExternalForm extAuth;
	
	// didn't receive ext auth
	if (fread(&extAuth, sizeof(extAuth), 1, stdin) != 1)
	{
		//NSLog(@"no ext auth given");
		exit(-1);
	}
	// restore ext auth
	if (AuthorizationCreateFromExternalForm(&extAuth, &auth))
	{
		//NSLog(@"could not restore ext auth");
		exit(-1);
	}
	
	AuthorizationItem right = {kPlugInSwitchRight, 0, NULL, 0};
	AuthorizationRights rightSet = {1, &right};
	AuthorizationFlags flags = kAuthorizationFlagDefaults | kAuthorizationFlagExtendRights;
	OSStatus status = AuthorizationCopyRights(auth, &rightSet, kAuthorizationEmptyEnvironment, 
		flags, NULL);
	if (status != 0)
	{
		//NSLog(@"could not create rights structure");
		exit(-1);
	}

	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
	
	NSMachPort *sendPort = (NSMachPort *)[[NSMachBootstrapServer sharedInstance] 
		portForName:kConnectionName];
	
	Worker *worker = [[Worker alloc] init];
	NSConnection *connection = [[NSConnection alloc] 
		initWithReceivePort:(NSPort *)[[sendPort class] port] 
		sendPort:sendPort];
	[[connection rootProxy] setProtocolForProxy:@protocol(WorkerDelegate)];
	worker.delegate = (NSObject <WorkerDelegate> *)[connection rootProxy];
	[worker awake];

	[runLoop run];
	
	[connection invalidate];
	[connection release];
	[worker release];
	[pool drain];
	[pool release];
	return 0;
}